# -*- coding:utf-8 -*-
"""

@author: liandyao
@date: 2025/1/6 21:44
"""
import random

from selenium.webdriver.support import expected_conditions as EC

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

from selenium.webdriver.support.wait import WebDriverWait

import pymysql


# Step 3: 存储到 MySQL
# 数据库配置
db_config = {
    'host': '127.0.0.1',
    'user': 'root',
    'password': '123',
    'database': 'mymusic'
}

# 连接到 MySQL
connection = pymysql.connect(**db_config)
cursor = connection.cursor()

# 创建表（如果不存在）
cursor.execute('''  
    CREATE TABLE IF NOT EXISTS dati_beautiful_girl (  
        id BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',  
        bg_url VARCHAR(100) COMMENT '网址',  
        bg_title VARCHAR(100) COMMENT '标题',    
        remark VARCHAR(255) COMMENT '备注',  
        create_time DATETIME COMMENT '创建时间',  
        sort BIGINT DEFAULT 99 COMMENT '排序',   
        tags VARCHAR(255) COMMENT '标签分类',  
        exp VARCHAR(255) COMMENT '扩展字段',  
        PRIMARY KEY (id)  
    ) CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='对联表'  
''')
def insertDb(couplets):
    # 插入数据
    for url, title, tags in couplets:

        cursor.execute('''  
            INSERT INTO dati_beautiful_girl (bg_url, bg_title,tags)  
            VALUES (%s, %s, %s)  
        ''', (url, title, tags))

    connection.commit()


def getUrl(url,tags):
    # 创建 WebDriver 实例
    driver = webdriver.Chrome()
    driver.get(url)

    try:
        # 找到 id=container 的 div，获取所有 a 超链接
        container = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, "container"))
        )
        links = container.find_elements(By.TAG_NAME, "a")
        # 用于存储所有 img 的 src 和 alt 属性
        image_data = []

        for link in links:
            link_href = link.get_attribute("href")
            if link_href:  # 确保链接存在
                current_window = driver.current_window_handle  # 记录当前窗口句柄
                link.click()  # 点击链接
                time.sleep(5)
                # 等待新窗口打开
                WebDriverWait(driver, 10).until(EC.new_window_is_opened([current_window]))

                # 切换到新窗口
                WebDriverWait(driver, 10).until(lambda d: len(d.window_handles) == 2)  # 等待新窗口出现
                new_window = [window for window in driver.window_handles if window != current_window][0]
                driver.switch_to.window(new_window)

                # 在新窗口中执行操作，例如查找 ul 元素
                try:
                    ul_element = WebDriverWait(driver, 10).until(
                        EC.presence_of_element_located((By.TAG_NAME, "ul"))
                    )
                    li_elements = ul_element.find_elements(By.TAG_NAME, "li")
                    # 提取 img 的 src 和 alt 属性
                    for li in li_elements:
                        img = li.find_element(By.TAG_NAME, "img")
                        image_src = img.get_attribute("src")
                        image_alt = img.get_attribute("alt")
                        image_data.append((image_src, image_alt,tags))  # 存储结果
                        print(f"Image URL: {image_src}, Alt Text: {image_alt}")
                except Exception as e:
                    print(f"Error locating ul element: {e}")

                    # 关闭新窗口
                driver.close()

                # 切换回原窗口
                driver.switch_to.window(current_window)
        return image_data

    finally:
        driver.quit()



if __name__ == '__main__':
    urls = [] ;
    for i in range(20,247):
        url = f"https://desk.tooopen.com/meinv_3_{i}.html"
        urls.append(url)
        print(url)

    for url in urls:
        print(url)
        time.sleep(random.randint(2,6))
        data = getUrl(url,"超性感")
        insertDb(data)